<template>
  <h2 v-if="firstView">输入用户名搜索</h2>
  <h2 v-else-if="loading">Loading......</h2>
  <h2 v-else-if="errorMsg">{{errorMsg}}</h2>
  <div class="row" v-else>
    <div class="card" v-for="(item,index) in users" :key="index">
      <a :href="item.repoUrl" target="_blank">
        <img :src="item.avatar_url" style='width: 100px'/>
      </a>
      <p class="card-text">{{item.repoName}}</p>
    </div>
  </div>
</template>

<script>
  import PubSub from 'pubsub-js';
  import Axios from 'axios';

  export default {
    name: "Main",
    data() {
      return {
        firstView: true,
        loading: false,
        users: null,
        errorMsg: ''
      }
    },
    mounted() {
      // 订阅消息
      PubSub.subscribe('searchRepo', (msg, searchName) => {
        const url = `https://api.github.com/search/repositories?q=${searchName}&sort=stars`;

        // 更新状态（请求中）
        this.firstView = false;
        this.loading = true;
        this.users = null; // 清空数据
        this.errorMsg = null;

        // 发送ajax 获取数据
        Axios.get(url).then(({data}) => {
          // 修改数据结构
          this.users = data.items.map(item => {
            return {
              repoUrl: item.html_url,
              repoName: item.name,
              avatar_url: item.owner.avatar_url,
            }
          })

          // 成功，更新状态（成功）
          this.loading = false;
        }).catch(err => {
          // 失败，更新状态（失败）
          this.loading = false;
          this.errorMsg = err;
        });
      })
    }
  }
</script>

<style scoped>
  .card {
    float: left;
    width: 33.333%;
    padding: .75rem;
    margin-bottom: 2rem;
    border: 1px solid #efefef;
    text-align: center;
  }

  .card > img {
    margin-bottom: .75rem;
    border-radius: 100px;
  }

  .card-text {
    font-size: 85%;
  }

</style>
